package com.blog.backend.utils;

import com.blog.backend.config.CodeMsg;
import com.blog.backend.exception.GlobalException;
import com.blog.backend.vo.FileVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;

@Slf4j
@Component
public class FileUploadUtil {

    @Autowired
    private AppProperties appProperties;

    public  FileVo uploadFile(MultipartFile multipartFile){
        //判断文件是否为空
        FileVo fileVo = new FileVo();
        if (null == multipartFile || 0 == multipartFile.getSize()) {
            throw new GlobalException(CodeMsg.FILE_ERROR);
        }
        //获取
        String filename = System.currentTimeMillis()+multipartFile.getOriginalFilename();
        String contentType = multipartFile.getContentType();
        long size = multipartFile.getSize();//字节
        log.info("收到的请求文件信息：原生文件名：{},文件类型：{},文件大小：{}", filename, contentType, size);
        //获取文件后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        //判断配置的文件列表里是否支持该文件类型
        if (!ArrayUtils.contains(appProperties.getFileTypeArray(), suffix)) {
            throw new GlobalException(CodeMsg.FILE_FORMAT_ERROR);
        }
        double fileSize = size / 1024.0;//单位kb
        if (fileSize > appProperties.getMaxFileSize()) {
            throw new GlobalException(CodeMsg.FILE_SIZE_ERROR);
        }
        //创建文件存储路径按年月分类
        //获取年份
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
       String path= appProperties.getUploadPath()+"/"+year+"/"+month+"/";
        //构建文件对象
        File file = new File(path);
        //文件目录不存在则递归创建目录
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                log.error("创建文件夹异常");
                throw new GlobalException(CodeMsg.ERROR);
            }
        }
        InputStream ins = null;
        FileOutputStream outs = null;
        try {
            //获取文件输入流
            ins = multipartFile.getInputStream();
            //构建文件输出流
            outs = new FileOutputStream(path + filename );
            int len;
            byte[] bytes = new byte[1024];
            //读取一个bytes的文件内容
            while ((len = ins.read(bytes)) != -1) {
                outs.write(bytes, 0, len);
            }
            outs.close();
            log.info("上传成功：{}", path + filename );
            fileVo.setFileName(filename);
            fileVo.setFileUrl(appProperties.getShowPath()+"/"+year+"/"+month+"/"+filename);
            fileVo.setRealPath(path + filename );
        } catch (IOException e) {
            log.error("文件上传异常");
            e.printStackTrace();
        } finally {
            try {
                if (outs != null) {
                    outs.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException e) {
                log.error("关闭流异常");
                e.printStackTrace();
            }
        }
        return fileVo;
    }


}
